<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="学生" prop="studentId">
        <el-cascader
          class="w-full"
          v-model="formData.studentId"
          :options="classList"
          :props="cascaderProps"
          clearable
          filterable
          placeholder="请选择学生"
        />
      </el-form-item>

      <el-form-item label="序列号" prop="imei">
        <el-input v-model="formData.imei" placeholder="请输入序列号" />
      </el-form-item>
      <el-form-item label="NFC号" prop="nfcCode">
        <el-input v-model="formData.nfcCode" placeholder="请输入NFC号" />
      </el-form-item>
      <!-- <el-form-item label="MAC地址" prop="macCode">
        <el-input v-model="formData.macCode" placeholder="请输入MAC地址" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DeviceKidbandApi, DeviceKidband } from '@/api/school/smartDevice/kidBand'
import { ClassesApi } from '@/api/school/classes'
import { StudentApi } from '@/api/school/student'
import { defaultProps } from '@/utils/tree'

/** 闸机卡片 表单 */
defineOptions({ name: 'DeviceGateCardForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData: any = ref({
  id: undefined,
  imei: undefined,
  nfcCode: undefined,
  macCode: undefined,
  studentId: undefined
})
const formRules = reactive({
  imei: [{ required: true, message: '序列号不能为空', trigger: 'blur' }],
  nfcCode: [{ required: true, message: 'NFC号不能为空', trigger: 'blur' }],
  // macCode: [{ required: true, message: 'MAC地址不能为空', trigger: 'blur' }],
  studentId: [{ required: true, message: '学生不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const classList = ref([]) // 班级列表

// 级联选择器属性
const cascaderProps: any = {
  ...defaultProps,
  lazy: true,
  emitPath: true,
  lazyLoad: async (node, resolve) => {
    const { level, data } = node
    // 二级节点（学生）需要懒加载
    if (level === 2) {
      try {
        const list = await StudentApi.getSimpleStudentList(data.id)
        list.forEach((item) => {
          item.id = item.id
          item.name = item.studentName
          item.leaf = true
        })
        resolve(list)
      } catch (e) {
        console.error(e)
        resolve([])
      }
    } else {
      resolve([])
    }
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number, options?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceKidbandApi.getDeviceKidband(id)
      // 如果是编辑模式，需要设置级联选择器的值
      if (formData.value.studentId && formData.value.classId && formData.value.schoolCode) {
        formData.value.studentId = [
          formData.value.schoolCode,
          formData.value.classId,
          formData.value.studentId
        ]
      }
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.studentId = options?.cascaderValue.filter((item) => item)
  }
  classList.value = await ClassesApi.getClassesList()
  classList.value.forEach((item: any) => {
    if (item?.name?.includes('景秀')) {
      item.id = 'jingxiu'
    } else {
      item.id = 'yuanhu'
    }
  })
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 处理学生ID数据
    const data: any = {
      id: formData.value.id,
      imei: formData.value.imei,
      nfcCode: formData.value.nfcCode,
      macCode: formData.value.macCode,
      studentId: formData.value.studentId
    }
    if (Array.isArray(data.studentId) && data.studentId.length === 3) {
      // data.schoolCode = data.studentId[0]
      // data.classId = data.studentId[1] // 班级ID
      data.studentId = data.studentId[2] // 学生ID
    }

    if (formType.value === 'create') {
      await DeviceKidbandApi.createDeviceKidband(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceKidbandApi.updateDeviceKidband(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    cardNumber: undefined,
    studentId: undefined
  }
  formRef.value?.resetFields()
}
</script>
